<?php

!defined('IN_SYSTEM') && exit('Access denied');

class productControlPage extends commonControlPage {

    /** privates **/
    private function getNoRelationImages() {
        $this->view->no_relation_images = $_ENV['db']->fetchAll("SELECT * FROM `product_image` WHERE `product_id` = '0'");
    }

    /**
     * 商品列表
     *
     */
    public function listModule() {
        $rowset = $_ENV['db']->fetch("SELECT COUNT(product_id) as `total` FROM `product`");
        $total = $rowset['total'];
        unset($rowset);

        $pager = new class_pager();
        $pager->setConfig((int)$_GET['page_no'],$total);
        $pager->setUrl('?app='.APP.'&mod='.MOD.'&page_no=TPT','TPT');

        $this->view->products = (array)$_ENV['db']->fetchAll('SELECT * FROM `product` ORDER BY `product_id` DESC LIMIT '.$pager->getLimit().' OFFSET '.$pager->getOffset());
        $this->view->pager = $pager->output();
        $this->showMainPage('admincp/product_list');
    }

    /**
     * 商品导入导出
     */
    public function importModule() {
        if (POST) {

            //$file_name = __PATH__.'/tmp/'.uniqid();
//            $upload = new class_upload();
//            $upload->setAllowExt('csv');
//            $or = $upload->upload('file',$file_name);
//            if (!$or) {
//                $this->showMessage($upload->getError());
//            }
//
//            $file_name .= '.'.$upload->getFileExt();
//
//            $data = file_get_contents($file_name);
//            if (!$data) {
//                $this->showMessage('系统内部错误');
//            }
//
//            $data = explode("\n",$data);
//            array_shift($data);
//            $data = array_filter($data);

			header("Content-type:text/html;charset=utf-8");
			if(!$_FILES)
			{
				$this->showMessage('请选择导入文件!','back');		
			}
			$data = class_excel::ImportCsv();


			$_ENV['db']->beginTransaction();

            foreach ($data as $key=>$item) 
			{
				if($key==0)
				{//标头跳过
					continue;
				}
                //$item = iconv('gbk','utf-8',$item);
				//$item = str_replace($item, " ", "");
				list($id,$n1,$code,$name,$systemtype,$n3,$n4,$n5,$n6,$n7) = explode(',',$item);
				
				if (!$name) {
                	/*[回滚事务]*/
				 	$_ENV['db']->rollback();
                    $this->showMessage('编号['.$id.']名称不能为空');
                }
				
				$cid = productEntity::GetIDByCode($code);
				
				
				if(productEntity::IsExistName($name))
				{
					/*[回滚事务]*/
				 	$_ENV['db']->rollback();
                    $this->showMessage('编号['.$id.']名称['.$name.']已存在!');
				}
				
				$resultID = InsertTable('product',array(
												'name'=>$name,
												'systemtype' => $systemtype,
												//'mobile' => '',
												//'zip' => '',
												'cid'=>$cid,
												'code'=>$code,
												'desc' => '导入',
												'anum'=>0,
												'created_time' => time()
												));
            		if (!$resultID) 
                    {
                       /*[回滚事务]*/
				 		$_ENV['db']->rollback();
                        $this->showMessage('系统异常，导入失败');
                    }
				
				
                //list($name,$code,$cprice,$price,$num) = explode(',',$item);
//                if (!$name || !$code || !$price || !$cprice || !$num) {
//                    $this->showMessage('文件内容有误,请确认没有空字段');
//                }
//
//                if (!preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$cprice) || !preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$price)) {
//                    $this->showMessage('请确认所有价格格式正确');
//                }
//
//                $_ENV['db']->runSql("INSERT INTO `product` ".$this->buildSql(array(
//                        'name' => $name,
//                        'code' => $code,
//                        'price' => $price,
//                        'cprice' => $cprice,
//                        'num' => $num,
//                        'cid' => '0',
//                        'systemtype' => '',
//                        'bnum'=>$num,
//                        'bprice' => $price,
//                        'created_time' => time(),
//                        'anum' => '0'
//                    )));
            }
			$_ENV['db']->commit();
            $this->showMessage('导入成功');
            @unlink($file_name);
        } else {
            $this->showMainPage("admincp/product_import");
        }
    }
    public function exportModule() {
        if (POST) {
            $class_id = (int)$_POST['class_id'];
            
            $where = '';
            if ($class_id) {
                $product_class = class_cache::read('product_class');
                $cid = array($class_id,'0');
                foreach ((array)$product_class as $class) {
                    $path = ",{$class['path']},";
                    if (strpos($path,",{$class_id},")) {
                        $cid[] = $class['class_id'];
                    }
                }

                $where = ' where cid in ('.implode(',',$cid).')';
            }
            $products = $_ENV['db']->fetchAll("SELECT * FROM product {$where}");
            $csv = array();
            $csv[] = iconv('utf-8','GBK//TRANSLIT','名称,货号,成本,系统类型,当前库存,已售数量');
            foreach ((array)$products as $product) {
                $csv[] = iconv("utf-8",'GBK//TRANSLIT',"{$product['name']},{$product['code']},{$product['price']},{$product['systemtype']},{$product['num']},{$product['sold_num']}");
            }


            $csv = implode("\n",$csv);

            header("Content-type: text/csv; charset=gbk");
            header("Cache-Control: no-cache");
            header("Program: no-cache");
            header("content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=".uniqid().".csv");
            header("Expires: 0");
            header("Content-Length: ".strlen($csv));

            echo $csv;
            exit;
        } else {
            $category = new class_category();
            $product_class = $category->doList('product_class');
            $this->view->product_class = $product_class;
            $this->showMainPage("admincp/product_export");
        }
    }

    /**
     * 添加商品
     */
    public function addModule() {

        // 初始化上传对象
        $upload = new class_upload();
        $upload->setAllowExt('image');

        if(POST && AJAX) {
            $type = $_REQUEST['type'];
            if(in_array($type,array('image','product_image','deleteimage'))) {
                $this->processImage($type,$upload);
            } else if ('add' == $type) {
                $data = $this->productValidate();
                
                // insert
                $_ENV['db']->runSql("INSERT INTO `product` ".$this->buildSql(array(
						'name' => $data['name'],
						'code' => $data['code'],
                        'cid' => $data['object_id'],
						'systemtype' => $data['systemtype'],
						'default_imagehash' => $data['default_imagehash'],
						'price' => $data['sale_price'],
                        'cprice' => $data['price'],
						'desc' => $data['desc'],
						'num' => $data['num'],
						'created_time' => $_ENV['time'],
						'anum' => $data['num'],
						'aprice' => $data['price']
					)));
				$_ENV['db']->runSql("INSERT INTO `product_stock_history` ".$this->buildSql(array(
						'product_id' => $_ENV['db']->insertId(),
						'num' => $data['num'],
						'price' => $data['sale_price'],
						'created_time' => $_ENV['time']
					)));

                if (!empty($data['imagehashs'])) {
                    $product_id = $_ENV['db']->insertId();
                    $hashs = '\''.implode('\',\'',$data['imagehashs']).'\'';
                    $_ENV['db']->runSql("UPDATE `product_image` SET `product_id` = '{$product_id}' WHERE `hash` IN ({$hashs})");
                }
                $this->outputJson(1,'操作成功');
            }

            $this->outputJson(-403,'非法操作');
        }

        // 加载script
        $this->view->addScript('ajaxfileupload,editor/kindeditor,editor/zh_CN,cselector');

        // 加载模板
        $this->view->allow_ext = implode(',',$upload->getAllowExt());
        $this->view->product_class = $_ENV['db']->fetchAll("SELECT * FROM `product_class` WHERE `parent_id` = '0'");
        $this->view->systemtype = $_ENV['config']['systemtype'];
        $this->showMainPage('admincp/product_add');
    }
    public function modiModule() {
        $pid = (int)$_GET['product_id'];
        $upload = new class_upload();
        $upload->setAllowExt('image');

        $product = $_ENV['db']->fetch("SELECT * FROM `product` WHERE `product_id` = '{$pid}'");

        if (!$product) $this->showMessage('找不到指定商品',-404);

        if (POST && AJAX) {
            $type = $_REQUEST['type'];
            if ('modi' == $type) {
                $data = $this->productValidate($product);
                $data['object_id'] = $data['object_id']=='none'?$product['cid']:$data['object_id'];

                // update
                $sql = "UPDATE `product` SET `name` = '{$data['name']}',`code` = '{$data['code']}',`systemtype` = '{$data['systemtype']}',`default_imagehash` = '{$data['default_imagehash']}',`price` = '{$data['sale_price']}',`cprice`='{$data['price']}',`desc` = '{$data['desc']}',`num` = '{$data['num']}',`cid`='{$data['object_id']}' WHERE `product_id` = '{$pid}'";
                $_ENV['db']->runSql($sql);
                if (!empty($data['imagehashs'])) {
                    $hashs = '\''.implode('\',\'',$data['imagehashs']).'\'';
                    $_ENV['db']->runSql("UPDATE `product_image` SET `product_id` = '{$pid}' WHERE `hash` IN ({$hashs})");
                }

                $this->outputJson(1,'操作成功');
            } else if(in_array($type,array('image','product_image','deleteimage'))){
                $this->processImage($type,$upload);
            }

            $this->outputJson(-403,'非法操作');
        }

        // 获取图片
        $product_images = $_ENV['db']->fetchAll("SELECT * FROM `product_image` WHERE `product_id` = '{$pid}'");

        // 加载script
        $this->view->addScript('ajaxfileupload,editor/kindeditor,editor/zh_CN,cselector');

        $class_path = $_ENV['db']->fetchCol("SELECT path FROM `product_class` WHERE `class_id` = '{$product['cid']}'");
        $this->view->class_names = $_ENV['db']->fetchAll("SELECT class_name FROM `product_class` WHERE `class_id` IN ({$class_path},{$product['cid']})");
        $this->view->product_class = $_ENV['db']->fetchAll("SELECT * FROM `product_class` WHERE `parent_id` = '0'");

        // 加载模板
        $this->view->images = $product_images;
        $this->view->allow_ext = implode(',',$upload->getAllowExt());
        $this->view->systemtype = $_ENV['config']['systemtype'];
        $this->view->product = $product;
        $this->showMainPage('admincp/product_modi');
    }
    private function productValidate($object=array()) {
        $data = getRequests(array('name','code','price','default_imagehash','imagehashs','num','systemtype','object_id','sale_price'));
        $data['desc'] = htmlspecialchars(cstripslashes($_POST['desc']));
        $data['imagehashs'] = explode(',',$data['imagehashs']);

        // 商品名称判断
        $length = mb_strlen($data['name'],'UTF-8');
        if (!$length || $length > 100) {
            $this->outputJson(-400,'商品名称长度必须在100个字符以内','name');
        }
        // 系统类型判断
        if (!in_array($data['systemtype'],explode("\n",$_ENV['config']['systemtype']))) {
            $this->outputJson(-400,'系统类型错误');
        }
        // 商品分类判断
        if ('add' == $_POST['type'] || ('modi' == $_POST['type'] && $data['object_id']!='none')) {
            $class_id = $_ENV['db']->fetchCol("SELECT class_id FROM `product_class` WHERE `class_id` = '{$data['object_id']}'");
            if (!$class_id) {
                $this->outputJson(-400,'商品分类不存在');
            }
            $next_class = $_ENV['db']->fetchCol('SELECT class_id FROM `product_class` WHERE `parent_id` = \''.$data['object_id'].'\'');
            if ($next_class) {
                $this->outputJson(-400,'商品分类必须为最低级分类');
            }
        }
        // 货号判断
        $length = mb_strlen($data['code'],'UTF-8');
        if (!$length || $length > 200) {
            $this->outputJson(-400,'货号长度必须在200个字符以内','code');
        } else {
            $code =& $data['code'];
            $row = $_ENV['db']->fetchCol("SELECT `code` FROM `product` WHERE `code` = '{$code}' LIMIT 1");
            if ($row) {
                if ($object['code']!='' && $object['code']!=$row) {
                    $this->outputJson(-400,'货号已存在');
                }
            }
        }
        // 库存判断
        if (!preg_match('/^[\d]{1,200}$/',$data['num'])) {
            $this->outputJson(-400,'库存数量必须为数字且不能为空','code');
        }
        // 价格判断
        if (!preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$data['price'])) {
            $this->outputJson(-400,'成本价格格式填写错误','price');
        }
        if (!preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$data['sale_price'])) {
            $this->outputJson(-400,'销售价格格式填写错误','price');
        }
        // 详情判断
        if (empty($data['desc'])) {
            $this->outputJson(-400,'商品详情不能为空','desc');
        }

        return $data;
    }
    private function processImage($processType,$upload = '') {
        if (!$upload) {
            $upload = new class_upload();
            $upload->setAllowExt('image');
        }
        
        $hash = substr(md5(uniqid(1).makeOrderId()),8);
        switch ($processType) {
            case 'image':
                $data = array();

                $filepath = 'desc/'.date('Y/m')."/{$hash}";
                if (!$upload->upload('imgFile',ATTACH_PATH.$filepath)) {
                    $data['message'] = $upload->getError();
                    $data['error'] = 1;
                } else {
                    $data['error'] = 0;
                    $data['url'] = "./attach/{$filepath}.".$upload->getFileExt();
                    //$data['hash'] = $hash;
                }
                echo json_encode($data);exit;
            break;

            case 'product_image':
                $tmp_filepath = 'product/'.date('Y/m')."/{$hash}";

                if (!$upload->upload('pi',ATTACH_PATH.$tmp_filepath))
                    $this->outputJson(0,$upload->getError());

                // 初始化图片缩略图类
                $resize_image = new class_resize_image();

                // 对图像进行缩略
                $filext = $upload->getFileExt();
                $real_tmp_filepath = ATTACH_PATH."{$tmp_filepath}.{$filext}";

                // 大图缩略
                $resize_image->init($real_tmp_filepath);
                $resize_image->resize($_ENV['config']['thumb_bw'],$_ENV['config']['thumb_bh']);
                $resize_image->save(ATTACH_PATH."{$tmp_filepath}_big.{$filext}");
                // 小图缩略
                $resize_image->init($real_tmp_filepath);
                $resize_image->resize($_ENV['config']['thumb_sw'],$_ENV['config']['thumb_sh']);
                $resize_image->save(ATTACH_PATH."{$tmp_filepath}_small.{$filext}");

                // 入库
                $_ENV['db']->runSql("INSERT INTO `product_image` (`hash`,`filepath`,`ext`,`created_time`) VALUES ('{$hash}','".dirname($tmp_filepath)."','{$filext}','".time()."')");

                $this->outputJson(1,$hash,"./attach/{$tmp_filepath}_small.{$filext}");
            break;

            case 'deleteimage':
                $hash = $_POST['hash'];

                $rowset = $_ENV['db']->fetch("SELECT * FROM `product_image` WHERE `hash` = '{$hash}'");
                if (!empty($rowset)) {
                    $bpath = ATTACH_PATH.$rowset['filepath'].'/'.$rowset['hash'];
                    @unlink($bpath.'.'.$rowset['ext']);
                    @unlink($bpath.'_big.'.$rowset['ext']);
                    @unlink($bpath.'_small.'.$rowset['ext']);
                    $_ENV['db']->runSql("DELETE FROM `product_image` WHERE `hash` = '{$hash}'");
                }
                $this->outputJson(1,'操作成功');
            break;
        }
        $this->outputJson(-403,'非法操作');
    }
    public function doProductList() {
        $where = '1';
        $page = (int)$_GET['page_no'];
        $_GET['page_no'] = 'TPT';

		if ($_GET['searchtype'] && $_GET['keyword']) {
			$type =& $_GET['searchtype'];
			$keyword =& $_GET['keyword'];
			if ('code' == $type) {
				$where .= " and `code` = '{$keyword}' ";
			} else if('product_name' == $type) {
			    $where .= " and `name` LIKE '%{$keyword}%' ";
			} else if('systemtype' == $type) {
				$where .= " and `systemtype` = '{$keyword}'";
			}
		}


        $sql = "SELECT count(product_id) as total FROM `product` WHERE {$where}";
		
		
		if ($_GET['osc'] && $_GET['ost']) {
            $order = "order by `{$_GET['osc']}` {$_GET['ost']}";
        } else {
            $order = 'order by `product_id` desc';
        }

        $pager = new class_pager();
        $pager->setConfig($page,$_ENV['db']->fetchCol($sql));
        $pager->setUrl('?'.http_build_query($_GET),'TPT');

        $this->view->pager = $pager->output();
        $this->view->products = $_ENV['db']->fetchAll("SELECT * FROM `product` WHERE {$where} {$order}");
    }
}